package com.km.app.controller.param;

import com.km.app.util.ImageTools;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;

public class ResizeState implements ParamState {
    private final static Log log = LogFactory.getLog(CropState.class);
    private Integer width;
    private Integer height;
    private String srcPath;
    private String targetPath;

    public ResizeState(String srcPath) {
        this.srcPath = srcPath == null ? null : srcPath.trim();
    }

    @Override
    public File action(ParamContext context) {
        String[] var1 = context.getQuery().split(",");
        if (var1 == null || var1.length == 0) {
            return null;
        }
        if (this.srcPath == null || this.srcPath.length() == 0) {
            return null;
        }
        for (String var2 : var1) {
            if (var2 == null || var2.trim().length() == 0) {
                continue;
            }
            String[] var3 = var2.split("_");
            if (var3 != null && var3.length == 2) {
                if (var3[0].equals("width")) {
                    this.width = Integer.valueOf(var3[1]);
                }
                if (var3[0].equals("height")) {
                    this.height = Integer.valueOf(var3[1]);
                }
            }
        }
        if (this.width == null && this.height == null) {
            return null;
        }
        String var4 = this.srcPath.substring(0, this.srcPath.lastIndexOf("."));
        String var5 = this.srcPath.substring(this.srcPath.lastIndexOf("."));
        this.targetPath = var4 + "_resize_" + (this.width != null ? this.width : "0") + "x" + (this.height != null ? this.height : "0");
        if (var5 != null) {
            targetPath +=  var5;
        }
        File f = new File(targetPath);
        if (f.exists()) {
            return f;
        }
        try {
            ImageTools.resizeImage(this.srcPath, this.targetPath, this.width, this.height);
            return new File(this.targetPath);
        } catch (Exception e) {
            log.error(e);
            return null;
        }
    }
}
